package com.fg.cloud.framework.shiro.realm;

import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.fg.cloud.common.finals.UserType;
import com.fg.cloud.common.shiro.CustomLoginToken;
import com.fg.cloud.common.shiro.ShiroUser;
import com.fg.cloud.common.shiro.UserUtils;
import com.fg.cloud.framework.redis.RedisCacheManager;
import com.fg.cloud.manager.entry.factory.vo.FactoryUserVo;
import com.fg.cloud.manager.service.factory.FactoryUserService;
import com.fg.cloud.manager.service.system.MenuService;
import com.fg.cloud.manager.service.system.RoleService;
import com.google.common.collect.Sets;

/**
 * Description:厂商平台自定义shiro认证模块
 * @author around
 * @date 2017年8月15日上午11:33:20
 */
public class FactoryRealm extends AuthorizingRealm {
	
	private static Logger LOGGER = LoggerFactory.getLogger(FactoryRealm.class);

	@Autowired
    private FactoryUserService shiro_factoryUser;
    @Autowired
    private RoleService shiro_factoryRole;
    @Autowired
    private MenuService shiro_factoryMenu;
    
    private RedisCacheManager cacheManager;
    
    @Override
    public String getName() {
    	return UserType.FACTORY;
    }
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		LOGGER.info("Shiro-factory登录认证");
		
		getAuthenticationCache();
		
		CustomLoginToken token = (CustomLoginToken) authcToken;
		FactoryUserVo user = shiro_factoryUser.selectUserByUserName(token.getUsername());

		//账号不存在
        if (user == null) {
            throw new UnknownAccountException();
        }
        //密码错误
        if (!user.getPassword().equals(String.valueOf(token.getPassword()))) {
        	throw new IncorrectCredentialsException();
        }
        //账号未启用
        if (user.getStatus() != 1 || user.getIsDeleted() != 1) {
        	throw new DisabledAccountException();
        }
        
        /*List<String> roleList = shiro_factoryRole.findByUserId(user.getId());
        Set<String> roles = Sets.newHashSet();
        roles.addAll(roleList);*/
        //List<Resource> resource = shiro_factoryMenu.findByUserId(user.getId(), user.getUserType());
        ShiroUser shiroUser = new ShiroUser(user.getId(), user.getUserName(), user.getTrueName(), getName());
        //shiroUser.setResourceList(resource);
        //user.setMenuList(resource);
        user.setPassword(null);
        //修改用户session
        setCurrentUser(user);
        // 认证缓存信息，不做自定义加盐密码认证
        return new SimpleAuthenticationInfo(shiroUser, token.getPassword(), getName());
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//校验当前用户类型是否正确，正确则进入处理角色权限问题，否则跳出
		if (!principals.getRealmNames().contains(getName())) return null;
		
		//Cache<Object, AuthorizationInfo> cache = getAvailableAuthorizationCache();
		//Object obj = getAvailablePrincipal(principals);
		//Object key = getAuthorizationCacheKey(principals);
		
		//获取当前登录的用户
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
        Set<String> urlSet = shiro_factoryMenu.findMenuUrlByUserId(shiroUser.getId());
        Set<String> roles = shiro_factoryRole.findByUserId(shiroUser.getId());
        shiroUser.urlSet = urlSet;
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(urlSet);
        info.addRoles(roles);
        //追加厂商角色
        info.addRole(UserType.FACTORY);
		return info;
	}

	private void setCurrentUser(Object user){
        UserUtils.setCurrentUser(user);
    }
	
	public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }
	
	@Override
	protected void clearCache(PrincipalCollection principals) {
		super.clearCache(principals);
	}
	
	@Override
	protected void clearCachedAuthenticationInfo(PrincipalCollection principals) {
		super.clearCachedAuthenticationInfo(principals);
	}
	
	@Override
	protected void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		super.clearCachedAuthorizationInfo(principals);
	}

	public RedisCacheManager getCacheManager() {
		return cacheManager;
	}

	public void setCacheManager(RedisCacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}
	
	
	
}
